var adminClaszs;
var studyClaszs;
$(function () {
	$('#operateStudentDialog').hide();
	$('#showImportStudentsDialog').hide();
    loadAdminStudyClasz();
    initStudentGridData();
    initOther();
});

/* 加载学生的行政班与教学班下拉框数据 */
function loadAdminStudyClasz() {
    $.getJSON('clasz/all-admin-claszs', function (data) {
        adminClaszs = data;
    });
    $.getJSON('clasz/all-study-claszs', function (data) {
        studyClaszs = data;
    });
}

function reloadData() {
	if ($('#selectClasz').combobox('getValue') != '') {
		var classSelectType = $('#classSelectType').combobox('getValue');
		var claszId = $('#selectClasz').combobox('getValue');
		if (classSelectType == 1) {
			$('#studentDataGrid').datagrid({
			    url:'student/search-by-adminclass',
			    queryParams:{ adminClass: claszId }
			});
		} else {
			$('#studentDataGrid').datagrid({
			    url:'student/search-by-studyclass',
			    queryParams:{ studyClass: claszId }
			});
		}
	} else {
		$('#studentDataGrid').datagrid({
		    url:'student/all'
		});
	}
	loadAdminStudyClasz();
}

/* 初始化学生的数据表格 */
function initStudentGridData() {
    $('#studentDataGrid').datagrid({
        fitColumns: true,
        fit: true,
        idField: 'Id',
        sortName: 'Id',
        sortOrder: 'desc',
        rownumbers: false,
        singleSelect: true,
        pagination: true,
        border: false,
        url: "student/all",
        toolbar: '#tb',
        columns: [
            [
                {field: 'id', hidden:true}, // datagrid多选 getSelections ，必须使用idFiled这个字段
                {field: 'studentNumber', title: '学号', align: 'center', width: 50},
                {field: 'name', title: '姓名', align: 'center', width: 50},
                {field: 'sex', title: '性别', align: 'center', width: 10,
                    formatter: function (value, row, index) {
                        return sex[value];
                    }
                },
                {field: 'identityCardNumber', title: '身份证号码', align: 'center', width: 80},
                {field: 'birthday', title: '生日', align: 'center', width: 30},
                {field: 'nation', title: '民族', align: 'center', width: 30,
                    formatter: function (value, row, index) {
                        return nation[value - 1];
                    }
                },
                {field: 'executiveClass', title: '所在行政班', align: 'center', width: 80,
                    formatter:function(value,row){
                        if (value > 0) {
                            for(var i = 0; i < adminClaszs.length; i++) {
                                if (adminClaszs[i].id == value) {
                                    return adminClaszs[i].name;
                                }
                            }
                        } else
                            return '';
                    }
                },
                {field: 'teachingClass', title: '所在教学班', align: 'center', width: 80,
                    formatter:function(value,row){
                        if (value > 0) {
                            for(var i = 0; i < studyClaszs.length; i++) {
                                if (studyClaszs[i].id == value) {
                                    return studyClaszs[i].name;
                                }
                            }
                        } else
                            return '';
                    }
                },
                {field: 'operation', title: '操作', align: 'center', width: 80,
                    formatter: function (value, row, index) {
                        return "<a class='up' onclick='showOperateStudentDialog(\"修改\", " + index + ");'>修改</a><a class='re' onclick='showDeleteStudentDialog(" + index + ");'>删除</a><a class='sp' onclick='showPassword(" + index + ");'>显示密码</a>";
                    }
                }
            ]
        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        },
        onLoadSuccess: function() {
        	changeStyle();
        }
    });
    setDataGridPager($('#studentDataGrid'));
	$('#operateStudentDialog').show();
	$('#showImportStudentsDialog').show();
	$('#bj-radio').attr('checked', 'true');
	$('#bj').show();
	$('#xm').hide();
	$('#bj-radio').click(function() {
		$('#bj').show();
		$('#xm').hide();
	});
	$('#xm-radio').click(function() {
		$('#xm').show();
		$('#bj').hide();
	});
}

function initOther() {
    initComobox($('#sex'), sex);
    initComobox($('#nation'), nation);
    $('#classSelectType').combobox({
        valueField: 'id',
        textField: 'name',
        editable: false,
        data: [
          { "id":0, "name":"全部" },
          { "id":1, "name":"行政班" },
          { "id":2, "name":"教学班" }
        ],
        onSelect : function(record) {
        	var result = [];
        	if (record.id == 0) {
        		$('#selectClasz').combobox({disabled : true});
        		$('#selectClasz').combobox("setValue", null);
	        	reloadData();
        		return;
        	} 
    		$('#selectClasz').combobox({disabled : false});
        	if (record.id == 1) {
        		result = adminClaszs;
        	} else {
        		result = studyClaszs;
        	}
        	$('#selectClasz').combobox({
    			valueField: 'id',
    	        textField: 'name',
    	        editable: false,
    	        data: result,
    	        onSelect : function(item) {
    	        	reloadData();
    	        }
    		});
        }
    });
    //==================================//
    var $error = $('#error');
    var $xh = $('#studentNumber');
    $xh.focusout(function() {
    	if (!validNull($(this).val())) {
    		if ($('#xhNullError').html() == undefined) {
    			$error.append("<span id='xhNullError'>学号不能为空！&nbsp;&nbsp;</span>");
    		}
    		return;
    	} else {
    		$('#xhNullError').remove();
    	}
    	if (!validNumber($(this).val())) {
    		if ($('#xhNumError').html() == undefined) {
    			$error.append("<span id='xhNumError'>学号必须为数字！&nbsp;&nbsp;</span> ");
    		}
    		return;
    	} else {
    		$('#xhNumError').remove();
    	}
    });
    
    var $name = $('#name');
    $name.focusout(function() {
    	if (!validNull($(this).val())) {
    		if ($('#nameNullError').html() == undefined) {
    			$error.append("<span id='nameNullError'>姓名不能为空！&nbsp;&nbsp;</span>");
    		}
    		return;
    	} else {
    		$('#nameNullError').remove();
    	}
    });

    var $idno = $('#identityCardNumber');
    $idno.focusout(function() {
    	if (!validNull($(this).val())) {
    		if ($('#idnoNullError').html() == undefined) {
        		$('#idnoExistsError').remove();
    			$error.append("<span id='idnoNullError'>身份证号不能为空！&nbsp;&nbsp;</span>");
    		}
    		return;
    	} else {
    		$('#idnoNullError').remove();
    	}
    	if (!validIdNo($(this).val())) {
    		if ($('#idnoError').html() == undefined) {
        		$('#idnoExistsError').remove();
    			$error.append("<span id='idnoError'>身份证号格式不正确！&nbsp;&nbsp; ");
    		}
    		return;
    	} else {
    		$('#idnoError').remove();
    	}
    	if ($('#oldIdNo').text() != null && $('#oldIdNo').text() == $("#identityCardNumber").val()) {
    		$('#idnoExistsError').remove();
    		return;
    	}
    	$.ajax({
            type: 'POST',
            data: { "identityCardNumber": $("#identityCardNumber").val() },
            url: "student/exists",
            dataType: "json",
            cache: false,
            success: function (data) {
        		$('#idnoExistsError').remove();
                if (true == data.result) {
            		if ($('#idnoExistsError').html() == undefined) {
            			$error.append("<span id='idnoExistsError'>身份证号数据库中已经存在！&nbsp;&nbsp; ");
            			return;
            		}
                }
            }
        });
    });
}

function showOperateStudentDialog(operateName, index) {
    $('#oldIdNo').remove();
    $.getJSON('clasz/all-admin-claszs', function (data) {
        $('#executiveClass').combobox({
            valueField: 'id',
            textField: 'name',
            panelHeight: 150,
            editable: false,
            data: data
        });
        $.getJSON('clasz/all-study-claszs', function (data) {
            $('#teachingClass').combobox({
                valueField: 'id',
                textField: 'name',
                panelHeight: 150,
                editable: false,
                data: data
            });
            $('#operateStudentDialog').dialog({
                title: operateName + "学生信息",
                width: 516,
                height: 246,
                modal: true,
                buttons: [
                    {
                        text: operateName,
                        handler: function (params) {
                            operateStudent(operateName);
                        }
                    },
                    {
                        text: '取消',
                        handler: function () {
                            $('#operateStudentDialog').dialog('close');
                        }
                    }
                ],
                onClose: function() {
                	$('#error').empty();
                    $('#oldIdNo').remove();
                }
            });
            clearData();
            if (operateName == '修改') {
                var student = getSelectedRow('studentDataGrid', index);
                $("#id").val(student.id);
                $("#name").val(student.name);
                $("#sex").combobox('select', student.sex);
                $("#nation").combobox('select', student.nation - 1);
                $("#birthday").datebox('setValue', student.birthday);
                $("#identityCardNumber").val(student.identityCardNumber);
                $("#studentNumber").val(student.studentNumber);
                if (student.executiveClass > 0) {
                    $("#executiveClass").combobox('select', student.executiveClass);
                }
                if(student.teachingClass > 0) {
                    $("#teachingClass").combobox('select', student.teachingClass);
                }
                $('#operateStudentDialog').append("<span id='oldIdNo'>" + student.identityCardNumber + "</span>");
            }
        });
    });
}

function clearData() {
    $("#id").val("");
    $("#name").val("");
    $("#sex").combobox('select', 0);
    $("#nation").combobox('select', 0);
    $("#birthday").datebox('setValue', "");
    $("#identityCardNumber").val("");
    $("#studentNumber").val("");
    $("#executiveClass").combobox('select', null);
    $("#teachingClass").combobox('select', null);
}

function operateStudent(operationName) {
	if (!($.trim($('#error').html()) == '')) {
		$.messager.alert("警告", "请确保提交内容格式！", "warning");
		return;
	}
	$('#error').empty();
    var $xh = $('#studentNumber');
    var $name = $('#name');
    var $idno = $('#identityCardNumber');
	if ($.trim($xh.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
	if ($.trim($name.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
	if ($.trim($idno.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
    var tempUrl = "student/add";
    if (operationName === '修改') {
        tempUrl = "student/update";
    } else {
        $("#id").val(-999);
    }
    $.ajax({
        type: 'POST',
        data: {
            "id": $("#id").val(),
            "studentNumber": $("#studentNumber").val(),
            "identityCardNumber": $("#identityCardNumber").val(),
            "name": $("#name").val(),
            "birthday": $("#birthday").datebox('getValue'),
            "sex": $("#sex").combobox('getValue'),
            "nation": parseInt($("#nation").combobox('getValue')) + 1,
            "executiveClass": $("#executiveClass").combobox('getValue'),
            "teachingClass": $("#teachingClass").combobox('getValue')},
        url: tempUrl,
        dataType: "json",
        cache: false,
        error: function (jqXHR, textStatus, errorThrown) {
            $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        },
        success: function (data) {
            if (true == data.result) {
                $.messager.alert("操作提示", "学生信息操作完成！", "info", function () {
                    $('#operateStudentDialog').window("close");
                    gridReload($('#studentDataGrid'));
                });
            }
        }
    });
}

function showDeleteStudentDialog(index) {
    $.messager.confirm("警告", "确定删除选中学生？", function (data) {
        if (data) {
        	var student = getSelectedRow('studentDataGrid', index);
        	$.ajax({
        		type: 'POST',
        		data: {
        			"studentId": student.id
        		},
        		url: "student/remove",
        		dataType: "json",
        		cache: false,
        		error: function (jqXHR, textStatus, errorThrown) {
        			$.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        		},
        		success: function (data) {
        			if (true == data.result) {
    					loadAdminStudyClasz();
    					gridReload($('#studentDataGrid'));
        			} else {
                        $.messager.alert("操作提示", "删除学生信息异常！");
                    }
        		}
        	});
        }
    });
}

function showPassword(index) {
    var student = getSelectedRow('studentDataGrid', index);
    $.ajax({
        type: 'POST',
        data: {
        },
        url: "authentication/" + student.identityCardNumber,
        dataType: "json",
        cache: false,
        error: function (jqXHR, textStatus, errorThrown) {
            $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        },
        success: function (data) {
            if ("" == data.result) {
                $.messager.alert("操作提示", "未成查询学生密码！", "info");
            } else {
                $.messager.alert("操作提示", "学生[" + student.name + "]密码:" + data.result, "info");
            }
        }
    });
}

// ============================ //
function changeStyle() {
	$('.re').linkbutton({  
	    iconCls: 'icon-remove',
	    plain: true
	});  
	$('.up').linkbutton({  
	    iconCls: 'icon-edit',
	    plain: true
	});  
	$('.sp').linkbutton({  
	    iconCls: 'icon-help',
	    plain: true
	}); 
}

//显示导入界面
function showImportStudentsDialog(needReloadDataGrid) {
 $('#showImportStudentsDialog').dialog({
     width: 500,
     height: 300,
     modal: true,
     content: createFrame("importStudents"),
     buttons: [
         {
             text: '取消',
             handler: function () {
            	 closeImportStudentsDialog();
             }
         }
     ]
 });
}

//关闭导入界面
function closeImportStudentsDialog() {
	$('#showImportStudentsDialog').window('close');
    gridReload($('#studentDataGrid'));
}

function searchStudentByName() {
	if (undefined == $("#sName").val() || "" == $("#sName").val() || $.trim($("#sName").val()).length == 0) {
		$('#studentDataGrid').datagrid({
			url:'student/all'
		});
	} else {
		$('#studentDataGrid').datagrid({
			url:'student/student-by-name',
		    queryParams:{ name: $("#sName").val()}
		});
	}
}
